/*
 * Copyright 2011 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.bezrabotnih.cabinet.client.activity;


import java.util.List;


import net.bezrabotnih.cabinet.client.request.CabinetJobRequest;
import net.bezrabotnih.cabinet.client.request.CabinetRequestFactory;
import net.bezrabotnih.cabinet.client.request.CabinetUserAccountRequest;
import net.bezrabotnih.cabinet.client.ui.ApplicantsView;
import net.bezrabotnih.cabinet.client.ui.ApplicantsViewImpl;
import net.bezrabotnih.cabinet.client.ui.ApplicantBlockView;
import net.bezrabotnih.cabinet.client.ui.ProfileView;
import net.bezrabotnih.cabinet.client.ui.ProfileViewImpl;
import net.bezrabotnih.cabinet.client.ui.ProviderJobBlockView;
import net.bezrabotnih.client.managed.request.JobProxy;
import net.bezrabotnih.client.managed.request.UserAccountProxy;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.requestfactory.shared.Receiver;
import com.google.gwt.requestfactory.shared.ServerFailure;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.gwt.user.client.ui.SimplePanel;

/**
 * Activities are started and stopped by an ActivityManager associated with a container Widget.
 */
public class ApplicantsActivity extends AbstractActivity implements ApplicantsView.Presenter,ApplicantBlockView.Presenter {

	/**
	 * Sample property.
	 */
	private ApplicantsView view;
	private CabinetRequestFactory requestFactory;
	private PlaceController placeController;
	
	private UserAccountProxy currentUserAccountProxy;
	private ParentActivity parentActivity;
	private SimplePanel infoPanel;

	public ApplicantsActivity(CabinetRequestFactory requestFactory,PlaceController placeController,SimplePanel infoPanel) {
		
		this.requestFactory=requestFactory;
		this.placeController=placeController;
	    this.infoPanel=infoPanel;
	}

	@Override
	public void start(AcceptsOneWidget containerWidget, EventBus eventBus) {
		view = new ApplicantsViewImpl();
		view.setPresenter(this);
		containerWidget.setWidget(view.asWidget());
		initApplicants();
		
		
	}

	@Override
	public String mayStop() {
		return null;
	}

	/**
	 * @see ApplicantsView.Presenter#goTo(Place)
	 */
	public void goTo(Place place) {
		// TODO
	}
	
	
	@SuppressWarnings("deprecation")
	private void initApplicants(){
		
		
		requestFactory.cabinetUserAccountRequest().currentUserAccount().fire(new Receiver<UserAccountProxy>() {

			@Override
			public void onSuccess(UserAccountProxy userAccountProxy) {
				if (userAccountProxy!=null){
					ApplicantsActivity.this.currentUserAccountProxy=userAccountProxy;
			     	populateApplicants();
				}
				
			}
		});
			
		
	}

	@SuppressWarnings("deprecation")
	@Override
	public void confirmClicked(final String applicantId,final String jobId) {
		
		final CabinetJobRequest request=requestFactory.cabinetJobRequest();
		requestFactory.cabinetJobRequest().findJob(jobId).fire(new Receiver<JobProxy>() {
			@Override
			public void onSuccess(JobProxy jobProxy) {
				if (jobProxy!=null){
					
					JobProxy editableJobProxy=request.edit(jobProxy);
					editableJobProxy.setWinnerId(applicantId);
					
					request.persist().using(editableJobProxy).fire(new Receiver<Void>() {
						@Override
						public void onSuccess(Void response) {
							
							if (currentUserAccountProxy!=null){
                                  populateApplicants();
							}else{
                                 initApplicants();
							}
							if (parentActivity!=null) parentActivity.applicantsRefreshed();
							
							
						}
						
						@Override
						public void onFailure(ServerFailure error) {
							
							view.showFailureView(applicantId+jobId);
							
						}
					});
					
					
				}
				
			}
		});
		
	}

	@Override
	public void cancelClicked(String applicantId, String jobId) {
		// TODO Auto-generated method stub
		
	}

	@SuppressWarnings("deprecation")
	public void populateApplicants() {
		
	  if (ApplicantsActivity.this.currentUserAccountProxy!=null)	
		requestFactory.cabinetJobRequest().findJobsByProviderIdWithWinnerNull(ApplicantsActivity.this.currentUserAccountProxy.getId()).with("jobType").fire(new Receiver<List<JobProxy>>() {

			
			@Override
			public void onSuccess(final List<JobProxy> jobProxies) {
				view.clearApplicantsView();
				if (jobProxies!=null)
				for (int i=0;i<jobProxies.size();i++){
					
					final JobProxy jobProxy=jobProxies.get(jobProxies.size()-1-i);
					
					
					requestFactory.cabinetUserAccountRequest().findApplicantsByJobId(jobProxy.getId()).fire(new Receiver<List<UserAccountProxy>>() {

						String jobIdStr=jobProxy.getId();
						String jobNameStr=jobProxy.getName();
						String winnerIdStr=jobProxy.getWinnerId();
						
						@Override
						public void onSuccess(
								List<UserAccountProxy> userAccountProxies) {
							
						
						if (userAccountProxies!=null){
							for(int i=0;i<userAccountProxies.size();i++){
								UserAccountProxy userAccountProxy=userAccountProxies.get(userAccountProxies.size()-1-i);
								view.addApplicant(ApplicantsActivity.this,
										userAccountProxy,
										jobProxy,
										userAccountProxy.getId().equals(winnerIdStr));
								
								
								
							}
							
							}
						}
					});
					
					
				}
				
				
			}
		});
	}
	
	public void setParentActivity(ParentActivity parent){
		this.parentActivity=parent;
	}
	
	public interface ParentActivity{
		
		void applicantsRefreshed();
	}

	@Override
	public void showApplicant(UserAccountProxy userAccountProxy) {
		
		if (infoPanel!=null){

			ProfileView profileView=ProfileViewImpl.create();
			if (userAccountProxy.getAge()!=null) profileView.setAge(userAccountProxy.getAge());
			profileView.setCity("Санкт-Петербург");
			if (userAccountProxy.getName()!=null) profileView.setName(userAccountProxy.getName());
			if (userAccountProxy.getSex()!=null) profileView.setSex(userAccountProxy.getSex()==0);

			infoPanel.setWidget(profileView);
		}
		
	}

	@Override
	public void showJob(JobProxy jobProxy) {
		if (infoPanel!=null){

			ProviderJobBlockView jobBlockView=new ProviderJobBlockView(jobProxy);

			infoPanel.setWidget(jobBlockView);
		}
		
	}
	
	
	
}
